<?php

class UserController extends Zend_Controller_Action 
{
	public function init() 
	{
	   $auth = Zend_Auth::getInstance();
        
       if($auth->hasIdentity()) {
           $this->view->username = $auth->getIdentity()->userProfile->nickname;
       }
       
	   $this->view->headScript()->appendFile('/js/jquery.form.js');
	   $this->view->headScript()->appendFile('/js/formjs.js');
	   $this->view->headScript()->appendFile('/js/user.js');
	   $this->view->headLink()->appendStylesheet('/css/tooltip.css');
	   
	   //jscroll
	   $this->view->headScript()->appendFile('/js/jscroll/jquery.mousewheel.min.js');
       //$this->view->headScript()->appendFile('/js/jscroll/jquery.scrollable.js');
       //$this->view->headLink()->appendStylesheet('/css/scrolling-list.css');
	   
       //feedtree
       $this->view->headScript()->appendFile('/js/feedtree/jqueryFeedTree.js');
       $this->view->headLink()->appendStylesheet('/css/feedTreeStyle.css');
	}
	
	/**
	 * Lock Unlock user account
	 * - Ajax action
	 *  
	 * @return void
	 */
	public function setuserlockAction()
	{
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$translate = Zend_Registry::get("Zend_Translate");
		$localeMsg = $translate->translate("ajaxError");
		
        $resultArray = array('error'   => true,
                             'message' => $localeMsg);
        
        $isEnabled = $this->_getParam('valueToSet', 2);
        $userID = $this->_getParam('elementID', 0);
        
        if (($isEnabled >= 0 && $isEnabled < 2) && 0 < $userID) {
            
            $factory = Model_Factory::getInstance();
            $service = $factory->getUserService();
                    	
	        $user = new Model_Entity_User();
	        $user->setOid($userID);
	        $user->setIsEnabled($isEnabled);
	        
	        $service->setUserLock($user);
	        
	        $resultArray = array('error' => false);
        }

        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
	}
	
	/**
	 * Load the user history page
	 * - Ajax action
	 * 
	 * @return void
	 */
	public function loadusershistoryAction()
	{
		$this->_helper->layout->disableLayout();
                
        $this->view->feedUserForm = new Form_UserHistory();
	}
	
	/**
	 * Load user list in the history page
     * - Ajax action
     * 
	 * @return void
	 */
	public function loaduserslistAction()
	{
	    $this->_helper->layout->disableLayout();
        
	    $searchSession = new Zend_Session_Namespace('searchuser');
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $form = new Form_UserHistory();
            $post = $request->getPost();

            if ($form->isValid($post)) {
                $values = $form->getValues();
                
                $factory = Model_Factory::getInstance();
                $service = $factory->getUserService();
                
                if (0 == $this->_getParam('page', 0)) {
                    $searchSession->unsetAll();
                    $searchSession->isOpenID = $form->getValue('isOpenID');
                    $searchSession->isEnabled = $form->getValue('isEnabled');
                    $searchSession->contains = $form->getValue('contains');
                }
                
                $criteria = array();
                $criteria['isOpenID'] = $searchSession->isOpenID;
                $criteria['isEnabled'] = $searchSession->isEnabled;
                $criteria['contains'] = $searchSession->contains;
                
                $users = new Zend_Paginator($service->searchUsers($criteria));
                $users->setCurrentPageNumber($this->_getParam('page', 1));
                $users->setItemCountPerPage(5);
                $users->setPageRange(5);
                
                $this->view->users = $users;
            } else {
                $translate = Zend_Registry::get("Zend_Translate");
                $localeMsg = $translate->translate("invalidparam");
                $this->getResponse()->appendBody($localeMsg);
            }
        }		
	}
	
    /**
     * Show the user profile form quering the session for user information 
     * 
     * @return void
     */
    public function userprofileAction()
    {
    	$this->_helper->layout->disableLayout();
        $this->_helper->layout->setLayout('adminlayout');
    	
    	$userObj = Zend_Auth::getInstance()->getIdentity();
        $user = $userObj->getOptions();
        $userProfile = $userObj->getUserProfile()->getOptions();
        $role = $userObj->getRoles()->getOptions();
        
        $user = array_merge($user, array('openid_identifier' => $user['username']));
        unset($user['username']);
        $data = array_merge($user, $userProfile);
 
        //la setto a true se l'utente corrente è user e non admin
        $loadCategories = false;
        
        //la setto a true se l'utente è openID
        $loadpwd = false;
        if($user['isOpenID'] == 0) $loadpwd = true;
    
        $factory = Model_Factory::getInstance();
        $service = $factory->getCategoryService();

        $checkboxCat = array();
	    
        if($role['oid'] == 1 ){  
        	$loadCategories = true;    
	        $categories = $service->getCategories();
	        
	        foreach ($categories as $category) {
	            $catArray = $category->getOptions();
	            $checkboxCat += array($catArray['oid'] => $catArray['name']); 
	        }
        }

        $categoriesOfInterest = $service->getCategoriesOfInterest($userObj->oid);
        
        $catOfIID = array();
        
        foreach ($categoriesOfInterest as $cat) {
            $catOfIID[] = $cat->oid;
        }
        
        $form = new Form_UserProfile();
        $form->getElement('categoryFeedProfile')->setMultiOptions($checkboxCat);
        $form->populate($data);
        $form->user_oid->setValue($user['oid']);
        $form->profile_oid->setValue($userProfile['oid']);
        
        $form->getElement('categoryFeedProfile')->setValue($catOfIID);
        
        $this->view->formUserProfile = $form;
        $this->view->loadCategories = $loadCategories;
        $this->view->loadpwd = $loadpwd;
    }
    
    /**
     * Update user information
     * - Ajax action
     * 
     * @return void
     */
    public function updateprofileAction()
    {
        // Disable both view and layout
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();
        
        $request = $this->getRequest();
                
        if ($request->isPost()) {
            $form = new Form_UserProfile();
            $post = $request->getPost();
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                
                $factory = Model_Factory::getInstance();
                $service = $factory->getUserService();
                
                $profile = new Model_Entity_UserProfile($form->getValues());
                $profile->setOid($form->getValue('profile_oid'));
                
                $user = new Model_Entity_User($form->getValues());
                $user->setUsername($form->getValue('openid_identifier'));
                $user->setOid($form->getValue('user_oid'));
                $user->setUserProfile($profile);
                
                $service->edit($user);
                
                // Refresh session data with new ones from user update
                $auth = Zend_Auth::getInstance();
                $role = $auth->getStorage()->read()->roles;
                $user->setRoles($role);
                $auth->getStorage()->write($user);
                
            } else { // Validation failed
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else { // Forward to userprofile page if request is not in POST
            $this->_forward('userprofile');
        }
    }
    
    
    public function feedsuggestAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->layout->setLayout('adminlayout');
    }
}
